var consts = require('../../../util/consts');
var dispatcher = require('../../../util/dispatcher');

module.exports = function (app) { return new Handler(app); };
const Handler = function (app) { this.app = app; };
const handler = Handler.prototype;

// 分配给用户一个connector服务器
handler.entry = function (msg, session, next) {
    var uid = msg.uid;

    if (!uid) {
        next(null, {
            code: consts.Code.ERR
        });
        return;
    }
    // get all connectors
    var connectors = this.app.getServersByType('connector');

    if (!connectors || connectors.length === 0) {
        next(null, {
            code: consts.Code.ERR
        });
        return;
    }

    var res = dispatcher.dispatch(uid, connectors);
    if (!res) {
        next(null, {
            code: consts.Code.ERR,
            msg: consts.Msg.USER_NOT_FOUND
        });
    }
    next(null, {
        code: consts.Code.SUC,
        host: res.clientHost,
        port: res.clientPort
    });
};
